#include "boards.h"
#include "pinctrl.h"
#include "gpio.h"
#include "osal_debug.h"
#include "cmsis_os2.h"
#include "app_init.h"
#include "common_def.h"

#include "mydriver.h"

unsigned char switch_state = 0;
unsigned char loop_flag = 0;

// LED
#define CONFIG_BLINKY_PIN         31
void init_LED(void)
{
    uapi_pin_set_mode(CONFIG_BLINKY_PIN, HAL_PIO_FUNC_GPIO);
    uapi_gpio_set_dir(CONFIG_BLINKY_PIN, GPIO_DIRECTION_OUTPUT);
    uapi_gpio_set_val(CONFIG_BLINKY_PIN, GPIO_LEVEL_LOW);
}

void LED_on(void)
{
    uapi_gpio_set_val(CONFIG_BLINKY_PIN, GPIO_LEVEL_HIGH);
}

void LED_off(void)
{
    uapi_gpio_set_val(CONFIG_BLINKY_PIN, GPIO_LEVEL_LOW);
}
// EOF LED

static void *main_task(const char *arg)
{
    unused(arg);
    init_LED();
    init_max395();
    init_dac();

    switch_all_off(&switch_state);

    switch_on(&switch_state, 0); // choose channel 0 for FSR
    // switch_on(&switch_state, 1); // choose channel 1 for FSR
    // switch_on(&switch_state, 2); // choose channel 2 for FSR
    // switch_on(&switch_state, 3); // choose channel 3 for FSR
    // switch_on(&switch_state, 4); // choose channel 4 for FSR

    switch_on(&switch_state, 5); // choose 10k for TIA
    // switch_on(&switch_state, 6); // choose 30k for TIA
    // switch_on(&switch_state, 7); // choose 100k for TIA
    
    dac_set_voltage(500.0); // set DAC output to 500mV

    osal_printk("ready to go\r\n");

    while (1) {
        switch (loop_flag) {
            case 0: {
                int adc_voltage = 0;
                adc_voltage = adc_get_voltage();
                osal_printk("ADC voltage: %d\r\n", adc_voltage);
                osDelay(1000);
                break;
            }
            case 1: {
                break;
            }
            default: break;
        }    
    }

    return NULL;
}

static void main_entry(void)
{
    osThreadAttr_t attr;

    attr.name = "MainTask";
    attr.attr_bits = 0U;
    attr.cb_mem = NULL;
    attr.cb_size = 0U;
    attr.stack_mem = NULL;
    attr.stack_size = 0x1000;
    attr.priority = (osPriority_t)(17);

    if (osThreadNew((osThreadFunc_t)main_task, NULL, &attr) == NULL) {
        /* Create task fail. */
    }
}

/* Run the blinky_entry. */
app_run(main_entry);